package com.qiantu.phone.ui.fragment.device;

import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.RollerShutterSeek;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 *    desc   : 卷帘设备
 */
public final class RollerShutterFragment extends BaseDeviceFragment {

    private View btnOpen;
    private View btnPause;
    private View btnClose;
    private RollerShutterSeek mRollerShutterSeek;

    public static RollerShutterFragment newInstance() {
        RollerShutterFragment fragment = new RollerShutterFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_roller_shutter;
    }

    @Override
    protected void initView() {
        super.initView();
        mRollerShutterSeek = findViewById(R.id.roller_shutter_seek);
        btnOpen = findViewById(R.id.btn_open);
        btnPause = findViewById(R.id.btn_pause);
        btnClose = findViewById(R.id.btn_close);
        setOnClickListener(btnPause);
        btnOpen.setOnTouchListener(mOnTouchListener);
        btnClose.setOnTouchListener(mOnTouchListener);
        mRollerShutterSeek.setOnChangeListener(new RollerShutterSeek.OnChangeListener(){
            @Override
            public void onStartTrackingTouch() {

            }

            @Override
            public void onProgressChanged(int value) {

            }

            @Override
            public void onValueChanged(int progress) {
                int strokePercentage = 100 - progress;
//                DeviceState deviceState = mDevice.getStateData();
//                Integer oldStrokePercentage = deviceState.getStatus().getStrokepercentage();
//                if(Float.valueOf(oldStrokePercentage) != strokePercentage){
//                    strokePercentageOperation(strokePercentage);
//                }
                strokePercentageOperation(strokePercentage);
            }
        });
        updateView();
    }

    protected void updateView(){
        super.updateView();
        DeviceState deviceState = mDevice.getStateData();
        Integer strokePercentage = deviceState.getStatus().getStrokepercentage();
        Float progress = Float.valueOf(strokePercentage);
//        if(mDevice.isIsOnline()){
            mRollerShutterSeek.setEnabled(true);
            mRollerShutterSeek.setProgress(100 - progress.intValue());
//        }else{
//            mRollerShutterSeek.setEnabled(false);
//            mRollerShutterSeek.setProgress(0);
//        }
//        mRollerShutterSeek.setProgress(progress.intValue());
    }

    private long downTime;
    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    downTime = System.currentTimeMillis();
                    break;
                case MotionEvent.ACTION_MOVE:
                    //长按打开关闭
                    if(downTime != 0 && System.currentTimeMillis() - downTime > 600) {
//                        if(mVibratorManager == null){
//                            mVibratorManager = new VibratorManager(getContext());
//                        }
//                        mVibratorManager.longClickVibrator();
                        v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                        downTime = 0;
                        switch (v.getId()) {
                            case R.id.btn_open:
                                strokeStateOperation(2);
                                break;
                            case R.id.btn_close:
                                strokeStateOperation(1);
                                break;
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    //长按释放发送暂停
                    if(System.currentTimeMillis() - downTime > 600){
                        strokeStateOperation(3);
                    }else{
                        if(event.getX() > 0 && event.getX() < v.getWidth()
                            && event.getY() > 0 && event.getY() < v.getHeight()){
                            switch (v.getId()){
                                case R.id.btn_open:
                                    v.playSoundEffect(SoundEffectConstants.CLICK);
                                    strokeStateOperation(2);
                                    break;
                                case R.id.btn_close:
                                    v.playSoundEffect(SoundEffectConstants.CLICK);
                                    strokeStateOperation(1);
                                    break;
                            }
                        }
                    }
                    break;
            }
            return true;
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_pause:
                strokeStateOperation(3);
                break;
        }
    }

    /**
     * 调节开合度
     * @param strokePercentage
     */
    private void strokePercentageOperation(int strokePercentage){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.STROKE_PERCENTAGE, strokePercentage);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setStrokeStatePercentage(strokePercentage);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                mRollerShutterSeek.setProgress(100 - mDevice.getStrokePercentage());
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    /**
     * 开关调节开合度
     * @param strokeState
     */
    private void strokeStateOperation(int strokeState){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.STROKE_STATE, strokeState);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setStrokeState(strokeState);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }
}